#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
投资建议生成系统 - 第八步执行模块
整合所有分析结果，生成完整的投资分析报告和具体操作建议
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

class InvestmentRecommendationSystem:
    """投资建议生成系统"""
    
    def __init__(self):
        self.report_date = datetime.now().strftime('%Y年%m月%d日')
        
        # 投资风险等级定义
        self.risk_levels = {
            '保守型': {'min_score': 0, 'max_score': 40, 'description': '追求稳健收益，低风险偏好'},
            '稳健型': {'min_score': 40, 'max_score': 60, 'description': '平衡风险收益，中等风险偏好'},
            '进取型': {'min_score': 60, 'max_score': 80, 'description': '追求较高收益，中高风险偏好'},
            '激进型': {'min_score': 80, 'max_score': 100, 'description': '追求最高收益，高风险偏好'}
        }
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"📋 {title}")
        print(f"{'='*80}")
        
    def load_prediction_results(self, filename="trend_prediction_results.csv"):
        """加载趋势预测结果"""
        try:
            df = pd.read_csv(filename)
            return df.to_dict('records')
        except Exception as e:
            print(f"加载趋势预测结果失败: {e}")
            # 如果预测结果不存在，尝试加载其他结果文件
            try:
                df = pd.read_csv("final_investment_ranking.csv")
                return df.head(3).to_dict('records')
            except:
                return []
                
    def load_all_analysis_data(self):
        """加载所有分析数据"""
        try:
            data = {}
            
            # 加载各步骤结果
            file_mappings = {
                'screening': 'screening_results.csv',
                'technical': 'technical_analysis_results.csv', 
                'fundamental': 'fundamental_analysis_results.csv',
                'ranking': 'final_investment_ranking.csv',
                'deep_analysis': 'deep_analysis_results.csv',
                'prediction': 'trend_prediction_results.csv'
            }
            
            for key, filename in file_mappings.items():
                try:
                    df = pd.read_csv(filename)
                    data[key] = df.to_dict('records')
                    print(f"   ✅ 成功加载 {filename}")
                except Exception as e:
                    print(f"   ⚠️ 无法加载 {filename}: {e}")
                    data[key] = []
                    
            return data
            
        except Exception as e:
            print(f"加载分析数据失败: {e}")
            return {}
            
    def generate_executive_summary(self, all_data):
        """生成执行摘要"""
        prediction_data = all_data.get('prediction', [])
        ranking_data = all_data.get('ranking', [])
        
        if not prediction_data and not ranking_data:
            return "数据不足，无法生成执行摘要"
            
        # 使用预测数据或排序数据
        main_data = prediction_data if prediction_data else ranking_data[:3]
        
        summary = f"""
📊 **A股中长期投资分析系统 - 执行摘要**

🎯 **分析目标**: 从符合投资条件的A股中筛选出3只最具潜力的中长期投资标的

📋 **筛选条件**: 
• 市值 ≥ 50亿元
• 股价 4-20元区间
• 市盈率 > 0（盈利股票）
• 优先有年度分红记录

🏆 **推荐标的**:
"""
        
        for i, stock in enumerate(main_data[:3], 1):
            code = stock.get('code', '')
            name = stock.get('name', '')
            
            if 'target_price' in stock:  # 预测数据
                current_price = stock.get('current_price', 0)
                target_price = stock.get('target_price', 0)
                upward_prob = stock.get('upward_probability', 0)
                recommendation = stock.get('investment_recommendation', '')
                
                summary += f"   {i}. {code} {name} - 当前价: {current_price:.2f}元, 目标价: {target_price:.2f}元, 上涨概率: {upward_prob:.1f}%, 建议: {recommendation}\\n"
            else:  # 排序数据
                comprehensive_score = stock.get('comprehensive_score', 0)
                investment_rating = stock.get('investment_rating', '')
                
                summary += f"   {i}. {code} {name} - 综合评分: {comprehensive_score:.1f}/100, 投资评级: {investment_rating}\\n"
                
        return summary
        
    def analyze_portfolio_allocation(self, prediction_data):
        """分析投资组合配置"""
        if not prediction_data:
            return {}
            
        portfolio = {}
        total_score = 0
        
        for stock in prediction_data:
            code = stock.get('code', '')
            name = stock.get('name', '')
            upward_prob = stock.get('upward_probability', 0)
            target_change = stock.get('target_change_pct', 0)
            recommendation = stock.get('investment_recommendation', '')
            
            # 计算配置权重
            if recommendation in ['积极买入', '适量买入']:
                base_weight = 30 if recommendation == '积极买入' else 20
                prob_adjustment = upward_prob / 100 * 10
                return_adjustment = max(target_change / 10, -5)
                
                weight = base_weight + prob_adjustment + return_adjustment
                weight = max(5, min(weight, 40))  # 限制在5%-40%之间
            else:
                weight = 0
                
            portfolio[f'{code} {name}'] = {
                'weight': weight,
                'recommendation': recommendation,
                'upward_probability': upward_prob,
                'target_change': target_change
            }
            
            total_score += weight
            
        # 标准化权重
        if total_score > 0:
            for stock_info in portfolio.values():
                stock_info['normalized_weight'] = stock_info['weight'] / total_score * 100
        else:
            # 如果没有推荐买入的股票，平均分配观望权重
            for stock_info in portfolio.values():
                stock_info['normalized_weight'] = 100 / len(portfolio)
                
        return portfolio
        
    def generate_risk_assessment(self, all_data):
        """生成风险评估"""
        deep_data = all_data.get('deep_analysis', [])
        prediction_data = all_data.get('prediction', [])
        
        if not deep_data and not prediction_data:
            return "数据不足，无法进行风险评估"
            
        risk_factors = []
        risk_score = 50  # 基础风险评分
        
        # 分析波动性风险
        if deep_data:
            avg_volatility = sum(stock.get('annual_volatility', 20) for stock in deep_data) / len(deep_data)
            if avg_volatility > 35:
                risk_factors.append("高波动性风险：所选股票年化波动率较高")
                risk_score += 15
            elif avg_volatility > 25:
                risk_factors.append("中等波动性风险：股票波动性适中") 
                risk_score += 8
                
        # 分析预测风险
        if prediction_data:
            avg_confidence = sum(stock.get('upward_probability', 50) for stock in prediction_data) / len(prediction_data)
            if avg_confidence < 40:
                risk_factors.append("预测不确定性风险：上涨概率偏低")
                risk_score += 10
            elif avg_confidence > 70:
                risk_factors.append("过度乐观风险：需要保持谨慎")
                risk_score += 5
                
        # 分析集中度风险
        if len(prediction_data) <= 3:
            risk_factors.append("集中度风险：投资标的数量有限")
            risk_score += 8
            
        # 确定风险等级
        if risk_score < 50:
            risk_level = "较低风险"
        elif risk_score < 65:
            risk_level = "中等风险"  
        elif risk_score < 80:
            risk_level = "较高风险"
        else:
            risk_level = "高风险"
            
        return {
            'risk_score': risk_score,
            'risk_level': risk_level,
            'risk_factors': risk_factors
        }
        
    def generate_operation_strategy(self, prediction_data, portfolio_allocation):
        """生成操作策略"""
        if not prediction_data:
            return "数据不足，无法生成操作策略"
            
        strategies = []
        
        # 买入策略
        buy_stocks = [s for s in prediction_data if s.get('investment_recommendation') in ['积极买入', '适量买入']]
        if buy_stocks:
            strategies.append("🔸 **买入策略**:")
            for stock in buy_stocks:
                code = stock.get('code', '')
                name = stock.get('name', '')
                current_price = stock.get('current_price', 0)
                target_price = stock.get('target_price', 0)
                operation = stock.get('operation_suggestion', '')
                
                weight = portfolio_allocation.get(f'{code} {name}', {}).get('normalized_weight', 0)
                
                strategies.append(f"   • {code} {name}: 建议仓位 {weight:.1f}%, 当前价 {current_price:.2f}元, 目标价 {target_price:.2f}元")
                strategies.append(f"     操作建议: {operation}")
                
        # 观望策略
        hold_stocks = [s for s in prediction_data if s.get('investment_recommendation') == '观望为主']
        if hold_stocks:
            strategies.append("\\n🔸 **观望策略**:")
            for stock in hold_stocks:
                code = stock.get('code', '')
                name = stock.get('name', '')
                operation = stock.get('operation_suggestion', '')
                
                strategies.append(f"   • {code} {name}: {operation}")
                
        # 回避策略
        avoid_stocks = [s for s in prediction_data if s.get('investment_recommendation') == '建议回避']
        if avoid_stocks:
            strategies.append("\\n🔸 **回避策略**:")
            for stock in avoid_stocks:
                code = stock.get('code', '')
                name = stock.get('name', '')
                strategies.append(f"   • {code} {name}: 暂时回避，等待更好时机")
                
        return "\\n".join(strategies)
        
    def generate_timing_suggestions(self, prediction_data):
        """生成时机建议"""
        if not prediction_data:
            return "数据不足，无法生成时机建议"
            
        suggestions = []
        
        # 分析当前市场时机
        avg_upward_prob = sum(s.get('upward_probability', 0) for s in prediction_data) / len(prediction_data)
        avg_target_return = sum(s.get('target_change_pct', 0) for s in prediction_data) / len(prediction_data)
        
        if avg_upward_prob > 60 and avg_target_return > 5:
            market_timing = "当前时机较好，可适度增加投资"
        elif avg_upward_prob > 45 and avg_target_return > 0:
            market_timing = "当前时机一般，保持正常投资节奏"
        else:
            market_timing = "当前时机偏差，建议谨慎投资"
            
        suggestions.append(f"🔸 **市场时机**: {market_timing}")
        
        # 买入时机建议
        suggestions.append("\\n🔸 **买入时机建议**:")
        suggestions.append("   • 分批买入：建议分2-3次买入，降低时机风险")
        suggestions.append("   • 回调买入：股价回调3-5%时可考虑加仓")
        suggestions.append("   • 定期投资：可考虑定期定额投资，平滑成本")
        
        # 卖出时机建议
        suggestions.append("\\n🔸 **卖出时机建议**:")
        suggestions.append("   • 目标止盈：达到目标价位附近可考虑分批止盈")
        suggestions.append("   • 止损设置：建议设置10-15%的止损位")
        suggestions.append("   • 定期评估：每月重新评估投资逻辑是否发生变化")
        
        return "\\n".join(suggestions)
        
    def generate_final_report(self, all_data):
        """生成最终投资分析报告"""
        prediction_data = all_data.get('prediction', [])
        
        print(f"📋 正在生成完整投资分析报告...")
        
        # 生成各部分内容
        executive_summary = self.generate_executive_summary(all_data)
        portfolio_allocation = self.analyze_portfolio_allocation(prediction_data)
        risk_assessment = self.generate_risk_assessment(all_data)
        operation_strategy = self.generate_operation_strategy(prediction_data, portfolio_allocation)
        timing_suggestions = self.generate_timing_suggestions(prediction_data)
        
        # 组装完整报告
        report = f"""
════════════════════════════════════════════════════════════════════════════════
                    A股中长期投资分析系统 - 完整投资建议报告                    
════════════════════════════════════════════════════════════════════════════════

📅 **报告日期**: {self.report_date}
🎯 **分析周期**: 基于历史数据，预测未来1个月趋势
📊 **分析方法**: 筛选条件 + 技术分析 + 基本面分析 + 综合评分 + 趋势预测

{executive_summary}

📈 **投资组合配置建议**:
"""
        
        if portfolio_allocation:
            report += "\n💼 **资金配置方案**:\n"
            for stock_name, allocation in portfolio_allocation.items():
                weight = allocation.get('normalized_weight', 0)
                recommendation = allocation.get('recommendation', '')
                
                if weight > 0:
                    report += f"   • {stock_name}: {weight:.1f}% ({recommendation})\n"
                else:
                    report += f"   • {stock_name}: 暂不配置 ({recommendation})\n"
        else:
            report += "   暂无明确配置建议，建议观望\n"
            
        # 风险评估
        if isinstance(risk_assessment, dict):
            report += f"\n⚠️ **风险评估**:\n"
            report += f"   • 综合风险等级: {risk_assessment['risk_level']}\n"
            report += f"   • 风险评分: {risk_assessment['risk_score']}/100\n"
            report += f"   • 主要风险因素:\n"
            for factor in risk_assessment['risk_factors']:
                report += f"     - {factor}\n"
        else:
            report += f"\n⚠️ **风险评估**: {risk_assessment}\n"
            
        # 操作策略
        report += f"\n🎯 **具体操作策略**:\n{operation_strategy}\n"
        
        # 时机建议
        report += f"\n⏰ **投资时机建议**:\n{timing_suggestions}\n"
        
        # 重要提示
        report += f"""
⚠️ **重要风险提示**:
   • 本报告基于历史数据和技术分析生成，仅供投资参考
   • 股市有风险，投资需谨慎，过往业绩不代表未来表现
   • 请根据个人风险承受能力和投资目标制定投资策略
   • 建议咨询专业投资顾问，并定期调整投资组合
   • 严格执行风险控制措施，避免过度集中投资

📞 **后续跟踪**:
   • 建议每月重新运行分析系统，更新投资建议
   • 关注宏观经济变化对投资标的的影响
   • 定期评估投资组合表现，及时调整策略

════════════════════════════════════════════════════════════════════════════════
                                报告完成                                    
════════════════════════════════════════════════════════════════════════════════
"""
        
        return report
        
    def run_investment_recommendation(self):
        """运行投资建议生成系统"""
        self.print_header("第八步：投资建议生成 - 完整投资分析报告")
        
        print(f"📋 开始整合所有分析结果，生成投资建议...")
        
        # 加载所有分析数据
        all_data = self.load_all_analysis_data()
        
        if not any(all_data.values()):
            print("❌ 无法加载分析数据，请确保前面的步骤已正确执行")
            return None
            
        print(f"\n📊 数据加载统计:")
        for step, data in all_data.items():
            print(f"   • {step}: {len(data)} 条记录")
            
        # 生成最终报告
        final_report = self.generate_final_report(all_data)
        
        # 显示报告
        print(final_report)
        
        # 保存报告
        self.save_final_report(final_report)
        
        return {
            'report': final_report,
            'data': all_data,
            'generation_date': self.report_date
        }
        
    def save_final_report(self, report, filename="投资分析报告.md"):
        """保存最终报告"""
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(report)
            print(f"\n💾 完整投资分析报告已保存到 {filename}")
            return filename
        except Exception as e:
            print(f"保存报告失败: {e}")
            return None

if __name__ == "__main__":
    # 创建投资建议生成系统实例
    recommendation_system = InvestmentRecommendationSystem()
    
    # 执行投资建议生成
    result = recommendation_system.run_investment_recommendation()
    
    if result:
        print(f"\n🎉 第八步：投资建议生成执行完成！")
        print(f"   • 成功整合了所有分析步骤的结果")
        print(f"   • 生成了完整的投资分析报告")
        print(f"   • 提供了具体的投资操作建议")
        print(f"\n🏁 A股中长期投资分析系统 - 8步完整流程执行完成！")
        print(f"   ✅ 从股票筛选到投资建议，全流程分析完成")
        print(f"   ✅ 所有分析结果已保存为CSV和报告文件")
        print(f"   ✅ 可以开始根据建议进行投资决策")
    else:
        print(f"\n❌ 投资建议生成失败，请检查前面步骤的执行结果")
